package com.cloudcc.mobile.view.main.fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager.LayoutParams;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.bus.DataEvent;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.UpdateUserEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.cloudframe.util.ImageUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.ChatUser;
import com.cloudcc.mobile.entity.UserBasicInfoForUpdate;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.ContactPresenter;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.activity.NeweditorActivity;
import com.cloudcc.mobile.view.activity.UpdateInfoActivity;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.view.crop.Crop;
import com.cloudcc.mobile.view.crop.ICrop;
import com.cloudcc.mobile.view.crop.ShowSelectPictureModeActivity;
import com.cloudcc.mobile.view.dynamic.DynamicOneListActivity;
import com.cloudcc.mobile.view.main.MainUIActivity;
import com.cloudcc.mobile.widget.CloudCCTitleBar;
import com.cloudcc.mobile.widget.CloudCCTitleBar.OnTitleBarClickListener;
import com.litesuits.android.log.Log;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

/**
 * @Description: 首页关于我
 * @author wangzhiqiang
 * @date 2016-1-19 下午1:39:02
 * 
 */
public class MainMeFragment extends BaseFragment implements
		OnTitleBarClickListener, IContactUserInfo, IEventLife {

	@Bind(R.id.user_follow)
	ImageView user_follow;

	@Bind(R.id.user_logo)
	ImageView user_logo;

	@Bind(R.id.user_message)
	ImageView user_message;

	@Bind(R.id.user_name)
	TextView user_name;

	@Bind(R.id.user_company)
	TextView user_company;

	@Bind(R.id.user_attr_container)
	LinearLayout user_attr_container;

	@Bind(R.id.chat_me_info)
	RelativeLayout chat_me_info;

	@Bind(R.id.chat_me_liuyannum)
	TextView chat_me_liuyannum;// 留言

	@Bind(R.id.chat_me_zhushinum)
	TextView chat_me_zhushinum;// 收到回复

	@Bind(R.id.chat_me_likenum)
	TextView chat_me_likenum;// 收到的赞

	@Bind(R.id.user_email)
	TextView user_email;

	@Bind(R.id.user_phone)
	TextView user_phone;

	@Bind(R.id.user_mobile_phone)
	TextView user_mobile_phone;

	@Bind(R.id.user_address)
	TextView user_address;

	@Bind(R.id.user_dynamices)
	TextView user_dynamices;

	@Bind(R.id.headerbar)
	CloudCCTitleBar headerbar;

	private ChatUser user;

	private ContactPresenter mContactPresenter;

	private int TAKE_PHOTO = 100;
	private int CAT_PHOTO = 101;
	private int SETTING_BEIJING = 102;
	private int CAT_SETTING_BEIJING = 103;
	private String picPath;
	private Bitmap imgresult;
	private ImageView location, photo, topimg;
	public Bitmap imgphoto;
	private Button allBtn;

	@Override
	public void init() {
		super.init();
		register();
		mContactPresenter = new ContactPresenter(this);
		initViews();
		initHeader();
		initData();
		initBackground();
	}

	private void initViews() {
		// TODO Auto-generated method stub
		allBtn = (Button) findViewById(R.id.allmenubtn);
		allBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				EventEngine.post(new MenuToggleEvent(false, false));
			}
		});
		mText = (TextView) findViewById(R.id.individuation);
		mText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showWindow(arg0);
			}
		});

	}

	private void initHeader() {
		headerbar.setTitle("关于我");
		headerbar.setRightText("个性化");
		headerbar.setRightText("个性化");
		headerbar.setLeftImageResource(R.drawable.menu_btn);
		headerbar.setOnTitleBarClickListener(this);
		headerbar.completeProgress();
		user_message.setVisibility(View.INVISIBLE);
		user_follow.setVisibility(View.INVISIBLE);
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		refreshUserfromCache();
		refreshUserInfoFromNet();
	}

	/**
	 * 背景
	 */
	private void initBackground() {
		String aa = mContext.getCacheDir().getAbsolutePath() + File.separator
				+ UserManager.getManager().getUser().userId + ".png";
		Bitmap bitmap = ImageUtils.getBitmap(aa);
		if (bitmap != null) {
			chat_me_info.setBackgroundDrawable(new BitmapDrawable(bitmap));
		}

	}

	private DisplayImageOptions getUserLogoDisplayImageOptions() {
		DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
				.bitmapConfig(Bitmap.Config.RGB_565)
				.imageScaleType(ImageScaleType.EXACTLY)// default
				.build();
		return displayImageOptions;
	}

	/**
	 * 刷新用户
	 */
	private void refreshUserInfoFromNet() {
		mContactPresenter
				.getUserInfoChatter(UserManager.getManager().getUser().userId);
	}

	/**
	 * 根据缓存的数据显示
	 */
	private void refreshUserfromCache() {
		UserModel usermodel = UserManager.getManager().getUser();
		ChatUser chatUser = new ChatUser();
		String zero = String.valueOf(0);
		chatUser.setCommentednum(zero);
		chatUser.setPhone(usermodel.phone);
		chatUser.setFeedandcomnum(zero);
		chatUser.setPraisenum(zero);
		chatUser.setTitle(usermodel.roleName);
		chatUser.setEmail(usermodel.email);
		chatUser.setName(usermodel.userName);
		chatUser.setLastModifyDate(zero);
		chatUser.setCreateDate(zero);
		chatUser.setMobile(usermodel.mobilePhone);
		chatUser.setAddress("");
		chatUser.setAboutme("");
		user = chatUser;
		refreshUIAndData();
	}

	/**
	 * 头像切换成功
	 * 
	 * @param event
	 */
	public void onEventMainThread(UpdateUserEvent event) {
		Bitmap imgphoto = ((MainUIActivity) getActivity()).imgphoto;
		this.imgphoto = imgphoto;
		user_logo.setImageBitmap(imgphoto);
	}

	private void refreshLogo() {
		String userId = UserManager.getManager().getUser().userId;
		String url = UrlTools.getTopImage(userId);
		UserUtils.setLogoRound(url, user_logo,
				UserUtils.getBackGroudColorByUserIdHash(userId, mContext),
				UserUtils.getNickRowName(user.getName()), mContext);
	}

	@SuppressLint("NewApi")
	private void refreshUIAndData() {
		refreshLogo();
		// 容器
		user_attr_container.setVisibility(View.VISIBLE);

		chat_me_liuyannum.setText(user.getFeedandcomnum());
		chat_me_zhushinum.setText(user.getCommentednum());
		chat_me_likenum.setText(user.getPraisenum());

		// 关于
		user_name.setText(user.getName());
		user_company.setText(user.getEmail());
		user_email.setText(user.getEmail());
		user_phone.setText(user.getPhone());
		user_mobile_phone.setText(user.getMobile());
		user_address.setText(user.getAddress());

		// 关于我
		user_dynamices.setEnabled(true);

	}

	@OnClick(R.id.user_dynamices)
	public void clickDynamices() {
		if (user == null) {
			return;
		}
		Intent intent = new Intent(mContext, DynamicOneListActivity.class);
		intent.putExtra("userName", user.getName());
		intent.putExtra("userId", UserManager.getManager().getUser().userId);
		mContext.startActivity(intent);

	}

	@Override
	public int getLayoutId() {
		return R.layout.act_userinfo;
	}

	@Override
	public void onClickLeft(View v) {
		EventEngine.post(new MenuToggleEvent(false, false));
	}

	@Override
	public void onClickRight(View v) {
		showWindow(v);
	}

	@Override
	public void onGettedUser(DataEvent<ChatUser> event) {
		if (event.isError()) {
			return;
		}
		user = event.getData();
		refreshUIAndData();
	}

	private PopupWindow popupWindow;

	private TextView mText;

	private void showWindow(View parent) {
		dissmissPopuWindow();
		View contentView = View.inflate(mContext, R.layout.popup_item2, null);
		TextView setting_bg = (TextView) contentView
				.findViewById(R.id.setting_bg);
		TextView update_info = (TextView) contentView
				.findViewById(R.id.update_info);
		// 创建一个PopuWidow对象
		popupWindow = new PopupWindow(contentView,
				(int) DensityUtils.getScreenWidth(getActivity()) * 4 / 9,
				LayoutParams.WRAP_CONTENT);
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		WindowManager windowManager = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		int xPos = windowManager.getDefaultDisplay().getWidth()
				- popupWindow.getWidth() - 2;
		popupWindow.showAsDropDown(parent, xPos, 2);
		setting_bg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dissmissPopuWindow();
				Intent intent = new Intent(getActivity(),
						ShowSelectPictureModeActivity.class);
				startActivityForResult(intent, ICrop.REQUEST_MODEL);

			}
		});
		update_info.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dissmissPopuWindow();
				openUpdatePage();
			}
		});
	}

	private void openUpdatePage() {
		UserBasicInfoForUpdate userBasicInfoForUpdate = new UserBasicInfoForUpdate();
		Intent intent = new Intent(mContext, UpdateInfoActivity.class);
		// Intent intent = new Intent(mContext, NeweditorActivity.class);

		userBasicInfoForUpdate.setEmail(user.getEmail());
		userBasicInfoForUpdate.setMobile(user.getMobile());
		userBasicInfoForUpdate.setPhone(user.getPhone());
		userBasicInfoForUpdate.setTitle(user.getTitle());
		userBasicInfoForUpdate.setAddress(user.getAddress());
		userBasicInfoForUpdate.setAbout(user.getAboutme());
		userBasicInfoForUpdate.setImg(user.getImg());
		userBasicInfoForUpdate.setName(user.getName());
		userBasicInfoForUpdate.setImgphoto(imgphoto);
		intent.putExtra("chatuser", userBasicInfoForUpdate);//
		startActivityForResult(intent, 701);
	}

	private void dissmissPopuWindow() {
		if (popupWindow != null) {
			popupWindow.dismiss();
			popupWindow = null;
		}
	}

	private void beginCrop(Uri source) {
		Uri outputUri = Uri.fromFile(new File(mContext.getCacheDir(),
				UserManager.getManager().getUser().userId + ".png"));
		new Crop(source).output(outputUri).asSquare().start(this);
	}

	private void takeCam() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, ICrop.TAKE_CAMERA);
	}

	private void pickPic() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_PICK);
		intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, ICrop.TAKE_CAMERA);
	}

	private void handleCrop(int resultCode, Intent result) {
		if (resultCode == Activity.RESULT_OK) {
			Uri output = Crop.getOutput(result);
			try {
				Bitmap bitmap = MediaStore.Images.Media.getBitmap(
						mContext.getContentResolver(), Crop.getOutput(result));
				chat_me_info.setBackgroundDrawable(new BitmapDrawable(bitmap));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		} else if (resultCode == Crop.RESULT_ERROR) {
			Toast.makeText(mContext, Crop.getError(result).getMessage(),
					Toast.LENGTH_SHORT).show();
		}
	}

	@SuppressLint("SdCardPath")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("activityresultcode", 1 + " " + resultCode + requestCode);
		if (data == null) {
			Log.d("activityresultcode", 1 + " " + resultCode + requestCode
					+ "null");
			return;
		}
		if (requestCode == ICrop.REQUEST_MODEL) {// 获得图片的方式

			int model = data.getIntExtra(ICrop.PIC_OB_MODEL, 0);
			Log.d("activityresultcode", 1 + " " + resultCode + requestCode);

			switch (model) {
			case ICrop.SELECT_PIC_BY_TACK_PHOTO:
				takeCam();
				break;
			case ICrop.SELECT_PIC_BY_PICK_PHOTO:
				pickPic();
				break;
			default:
				break;
			}
		} else if (requestCode == ICrop.TAKE_CAMERA
				&& resultCode == Activity.RESULT_OK) {
			Log.d("activityresultcode", 1 + " " + resultCode + requestCode);

			beginCrop(data.getData());
		} else if (requestCode == ICrop.TAKE_CAMERA
				&& resultCode == Activity.RESULT_OK) {
			Log.d("activityresultcode", 1 + " " + resultCode + requestCode);

			beginCrop(data.getData());
		} else if (requestCode == Crop.REQUEST_CROP) {
			Log.d("activityresultcode", 1 + " " + resultCode + requestCode);

			handleCrop(resultCode, data);
		} else if (requestCode == 701 && resultCode == Activity.RESULT_OK) {
			Log.d("activityresultcode", 1 + " " + resultCode + requestCode);

			UserBasicInfoForUpdate basic = (UserBasicInfoForUpdate) data
					.getSerializableExtra("user.new");
			user.setEmail(basic.getEmail());
			user.setMobile(basic.getMobile());
			user.setPhone(basic.getPhone());
			user.setTitle(basic.getTitle());
			user.setAddress(basic.getAddress());
			user.setAboutme(basic.getAbout());
			UserModel user = UserManager.getManager().getUser();
			user.email = user.email;
			user.mobilePhone = user.mobilePhone;
			UserManager.getManager().saveUser(user);
			refreshUIAndData();
		} else {
			Log.d("activityresultcode", 1 + " " + resultCode + requestCode);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unRegister();
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}
}
